import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pp_uikit/pp_multi_select_sheet.dart';
import 'package:pp_uikit/pp_single_select_sheet.dart';
import 'package:pp_uikit/theme/pp_default_theme.dart';

enum PPDialogStyle {
  normal,
  orange,
  blue,
}

// 提示框类型
enum PPDialogType {
  // 普通类型
  normal,
  // 可输入类型
  textField,
}

class PPDialogTheme {
  /// Dialog背景
  static Color backgroundColor = Colors.white;

  /// Dialog 宽度
  /// 默认为 300
  static double dialogWidth = 300;

  /// 圆角
  static double radius = 8.0;

  /// 底部按钮高度
  /// 默认为 44.0
  static double buttonHeight = 44.0;

  /// 标题的文字对齐
  /// 默认为 [TextAlign.center]
  static TextAlign titleTextAlign = TextAlign.center;

  /// 内容文字的对齐
  /// 默认为 [TextAlign.center]
  static TextAlign contentTextAlign = TextAlign.center;

  /// 按钮边框颜色
  static Color buttonBorderColor = PPDefaultTheme.instance.brandPrimary;

  /// 按钮边框颜色（卖家样色）
  static Color buttonBorderColorSeller = const Color(0xFF4057EC);

  /// 按钮按钮渐变颜色 - 左
  static Color buttonLeftGradientColor = PPDefaultTheme.instance.gradientLeft;

  /// 按钮按钮渐变颜色 - 右
  static Color buttonRightGradientColor = PPDefaultTheme.instance.brandPrimary;

  /// 按钮按钮渐变颜色 - 左（卖家样色）
  static Color buttonLeftGradientColorSeller = const Color(0xFF4057EC);

  /// 按钮按钮渐变颜色 - 右（卖家样色）
  static Color buttonRightGradientColorSeller = const Color(0xFF4057EC);

  static TextStyle titleTextStyle = TextStyle(
    color: PPDefaultTheme.instance.colorTextBase,
    fontSize: 18,
    fontWeight: FontWeight.bold,
    decoration: TextDecoration.none,
  );

  static TextStyle contentTextStyle = TextStyle(
    color: PPDefaultTheme.instance.colorTextImportant,
    fontSize: 16,
    decoration: TextDecoration.none,
  );
}

/// 底部按钮的点击监听回调
typedef PPDialogActionsClickCallback = void Function(int index);

// ignore: must_be_immutable
class PPDialog extends AlertDialog {
  /// 标题文本
  final String? titleText;

  /// 内容控件
  final Widget? contentWidget;

  /// 内容文本
  final String? messageText;

  /// 底部按钮文案
  final List<String>? buttonList;

  final GestureTapCallback? onCancel;
  final GestureTapCallback? onConfirm;

  final Function(String)? onConfirmWithText;

  /// 底部按钮的点击监听回调
  final PPDialogActionsClickCallback? actionsCallback;

  /// 弹框样式
  final PPDialogStyle dialogStyle;

  /// 弹框类型
  final PPDialogType dialogType;

  /// 自动关闭窗口
  final bool autoCloseWhenButtonClick;

  final TextField? textField;

  PPDialog({
    Key? key,
    this.titleText,
    this.messageText,
    this.contentWidget,
    this.buttonList,
    this.onCancel,
    this.onConfirm,
    this.onConfirmWithText,
    this.actionsCallback,
    this.dialogStyle = PPDialogStyle.orange,
    this.dialogType = PPDialogType.normal, //默认买家样式
    this.autoCloseWhenButtonClick = true,
    this.textField,
  }) : super(key: key);

  var textFieldContent = "";

  @override
  Widget build(BuildContext context) {
    Widget dialogWidget = Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        // 标题widget
        if (titleText != null) _generateTitleWidget(context),
        // 内容widget
        if (_isShowContent()) _generateContentWidget(context),

        const SizedBox(height: 20),

        if (_hasActions()) _generateActionsWidget(context),
        if (_hasActions()) const SizedBox(height: 20),
      ],
    );

    return UnconstrainedBox(
      child: SizedBox(
        width: PPDialogTheme.dialogWidth,
        child: Material(
          color: PPDialogTheme.backgroundColor,
          shape: RoundedRectangleBorder(
            borderRadius:
                BorderRadius.all(Radius.circular(PPDialogTheme.radius)),
          ),
          child: dialogWidget,
        ),
      ),
    );
  }

  bool _isShowContent() {
    return contentWidget != null || messageText != null;
  }

  bool _hasActions() {
    return buttonList != null && buttonList!.isNotEmpty;
  }

  /// 标题widget
  Widget _generateTitleWidget(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(top: 20),
      child: Text(
        titleText!,
        overflow: TextOverflow.ellipsis,
        style: PPDialogTheme.titleTextStyle,
        textAlign: PPDialogTheme.titleTextAlign,
      ),
    );
  }

  /// 内容widget：以contentWidget为准，辅以message生成的Text
  Widget _generateContentWidget(BuildContext context) {
    if (contentWidget != null) {
      return contentWidget!;
    }
    if (dialogType == PPDialogType.textField) {
      return Padding(
        padding: const EdgeInsets.only(top: 20, left: 20, right: 20),
        child: Center(
          child: Row(
            children: [
              Text(
                messageText ?? "",
                style: PPDialogTheme.contentTextStyle,
                textAlign: PPDialogTheme.contentTextAlign,
              ),
              Expanded(
                child: Container(
                  margin: const EdgeInsets.only(left: 8),
                  padding: const EdgeInsets.only(left: 12, right: 12),
                  height: 32,
                  decoration: BoxDecoration(
                    borderRadius: const BorderRadius.all(Radius.circular(4)),
                    border: Border.all(
                      color: PPDefaultTheme.borderColor,
                      width: 1,
                    ),
                  ),
                  child: textField,
                ),
              ),
            ],
          ),
        ),
      );
    }
    return Padding(
      padding: const EdgeInsets.only(top: 20, left: 20, right: 20),
      child: Center(
        child: Text(
          messageText ?? "",
          style: PPDialogTheme.contentTextStyle,
          textAlign: PPDialogTheme.contentTextAlign,
        ),
      ),
    );
  }

  Widget _generateActionsWidget(BuildContext context) {
    int length = buttonList!.length;
    if (length == 1) {
      return Container(
        margin: const EdgeInsets.only(
          left: 20,
          right: 20,
        ),
        child: _buildMainButton(context, buttonList![0], 0),
      );
    } else if (length == 2) {
      return Row(
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          const SizedBox(width: 20),
          Expanded(
              child: _buildCancelButton(
            context,
            buttonList![0],
            0,
          )),
          Expanded(
            child: _buildMainButton(
              context,
              buttonList![1],
              1,
            ),
          ),
          const SizedBox(width: 20),
        ],
      );
    } else {
      return SizedBox(
        height: length * PPDialogTheme.buttonHeight + (length - 1) * 10,
        width: double.maxFinite,
        child: ListView.separated(
            shrinkWrap: true,
            physics: length > 6 ? null : const NeverScrollableScrollPhysics(),
            padding: const EdgeInsets.only(left: 10, right: 10),
            itemBuilder: (context, i) {
              return _buildMainButton(
                context,
                buttonList![i],
                i,
              );
            },
            separatorBuilder: (context, index) => const Divider(
                  height: 10.0,
                  color: Colors.transparent,
                ),
            itemCount: length),
      );
    }
  }

  Widget _buildCancelButton(BuildContext context, String text, int index) {
    return GestureDetector(
      child: Container(
        margin: const EdgeInsets.only(right: 10.0),
        height: PPDialogTheme.buttonHeight,
        alignment: Alignment.center,
        decoration: BoxDecoration(
            //外边框
            border: Border.all(
              color: dialogStyle == PPDialogStyle.orange
                  ? PPDialogTheme.buttonBorderColor
                  : PPDialogTheme.buttonBorderColorSeller,
              width: 1,
            ),
            //控件颜色
            color: Colors.white,
            //圆角
            borderRadius: BorderRadius.circular((21.0))),
        child: Text(
          text,
          style: TextStyle(
            color: dialogStyle == PPDialogStyle.orange
                ? PPDialogTheme.buttonBorderColor
                : PPDialogTheme.buttonBorderColorSeller,
            fontSize: 16,
          ),
        ),
      ),
      onTap: () {
        if (autoCloseWhenButtonClick) {
          Navigator.pop(context);
        }
        //取消弹窗
        if (actionsCallback != null) {
          actionsCallback!(index);
        } else if (onCancel != null) {
          onCancel!();
        }
      },
    );
  }

  Widget _buildMainButton(BuildContext context, String text, int index) {
    return GestureDetector(
        child: Container(
          height: PPDialogTheme.buttonHeight,
          alignment: Alignment.center,
          decoration: BoxDecoration(
              //控件颜色，渐变
              gradient: LinearGradient(
                begin: Alignment.centerLeft,
                end: Alignment.centerRight,
                colors: dialogStyle == PPDialogStyle.orange
                    ? [
                        PPDialogTheme.buttonLeftGradientColor,
                        PPDialogTheme.buttonRightGradientColor,
                      ]
                    : [
                        PPDialogTheme.buttonLeftGradientColorSeller,
                        PPDialogTheme.buttonRightGradientColorSeller,
                      ],
              ),
              //圆角
              borderRadius: BorderRadius.circular((21.0))),
          child: Text(text,
              style: const TextStyle(color: Colors.white, fontSize: 16)),
        ),
        onTap: () {
          if (autoCloseWhenButtonClick) {
            Navigator.pop(context);
          }
          if (dialogType == PPDialogType.normal) {
            if (actionsCallback != null) {
              actionsCallback!(index);
            } else if (onConfirm != null) {
              onConfirm!();
            }
          } else {
            if (actionsCallback != null) {
              actionsCallback!(index);
            } else if (onConfirmWithText != null) {
              onConfirmWithText!(textFieldContent);
            }
          }
        });
  }

  static void show(
    BuildContext context, {
    String? title,
    String? message,
    Widget? contentWidget,
    String? cancel = "取消",
    String confirm = "确定",
    List<String>? buttonList,
    GestureTapCallback? onCancel,
    GestureTapCallback? onConfirm,
    Function(String)? onConfirmWithText,
    PPDialogActionsClickCallback? actionsCallback,
    PPDialogStyle dialogStyle = PPDialogStyle.orange,
    PPDialogType dialogType = PPDialogType.normal, //默认买家样式
    bool isDismissible = true,
    bool autoCloseWhenButtonClick = true,
    bool hideActions = false, // 隐藏按钮
    TextField? textField,
  }) {
    var buttons = [
      if (cancel != null) cancel,
      confirm,
    ];
    if (buttonList != null) {
      buttons = buttonList;
    }
    if (hideActions) {
      buttons = [];
    }
    showDialog(
      context: context,
      barrierDismissible: isDismissible,
      builder: (BuildContext dialogContext) {
        var dialog = PPDialog(
          titleText: title,
          messageText: message,
          contentWidget: contentWidget,
          buttonList: buttons,
          onCancel: onCancel,
          onConfirm: onConfirm,
          onConfirmWithText: onConfirmWithText,
          actionsCallback: actionsCallback,
          dialogStyle: dialogStyle,
          dialogType: dialogType,
          textField: textField,
          autoCloseWhenButtonClick: autoCloseWhenButtonClick,
        );
        return PopScope(
          canPop: isDismissible,
          child: dialog,
        );
      },
    );
  }

  static void showCustomSheet(
    BuildContext context, {
    required Widget widget,
    double? height,
    bool isDismissible = true,
  }) {
    height ??= ScreenUtil().screenHeight * 3 / 5;

    showModalBottomSheet(
      context: context,
      isDismissible: isDismissible,
      backgroundColor: Colors.transparent,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(12),
          topRight: Radius.circular(12),
        ),
      ),
      isScrollControlled: true,
      builder: (ctx) {
        return SizedBox(
          height: height,
          child: widget,
        );
      },
    );
  }

  /// 底部单选弹窗
  static void showSingleSelectSheet(
    BuildContext context, {
    required String title,
    required List<String> items,
    double? titleFontSize = 16,
    dialogStyle = PPDialogStyle.orange,
    FontWeight? titleFontWeight = FontWeight.bold,
    int maxItemCounts = 9,
    int minItemCounts = 2,
    int? selectedIndex,
    TextAlign textAlign = TextAlign.center,
    String buttonTitle = "确认",
    Function(int)? onConfirm,
    bool isDismissible = true,
  }) {
    showModalBottomSheet(
      context: context,
      isDismissible: isDismissible,
      backgroundColor: Colors.transparent,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(12),
          topRight: Radius.circular(12),
        ),
      ),
      isScrollControlled: true,
      builder: (ctx) {
        return PPSingleSelectSheet(
          title: title,
          items: items,
          dialogStyle: dialogStyle,
          titleFontSize: titleFontSize,
          titleFontWeight: titleFontWeight,
          maxItemCounts: maxItemCounts,
          minItemCounts: minItemCounts,
          selectedIndex: selectedIndex,
          textAlign: textAlign,
          buttonTitle: buttonTitle,
          confirmFun: onConfirm,
        );
      },
    );
  }

  /// 底部多选弹窗
  static void showMultiSelectSheet(
    BuildContext context, {
    required String title,
    required List<String> items,
    Function(List<int>)? confirmFun,
    bool isDismissible = true,
  }) {
    showModalBottomSheet(
        context: context,
        isDismissible: isDismissible,
        backgroundColor: Colors.transparent,
        shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(12),
            topRight: Radius.circular(12),
          ),
        ),
        isScrollControlled: true,
        builder: (ctx) {
          return PPMultiSelectSheet(
            title: title,
            items: items,
            confirmFun: confirmFun,
          );
        });
  }
}
